<?php if(!defined('OCTOMS')){header('HTTP/1.1 403');die('{"error":"forbidden"}');}
/*
 * @package       OctoMS.com
 * @subpackage    DesignJotter
 * @link          http://DesignJotter.com
 * @copyright     Copyright 2012, Valentino-Jivko Radosavlevici (http://valentino.radosavlevici.com)
 * @license       GPL v3.0 (http://www.gnu.org/licenses/gpl-3.0.txt)
 * 
 * Redistributions of files must retain the above copyright notice.
 * 
 * @since         OctoMS 0.0.1
 */
	
	/*
	 * Settings library
	 * 
	 * @link http://octoms.com/doc/settings_l
	 * 
	 * @package OctoMS
	 * @subpackage WP-OctoMS
	 * @version 0.1
	 * 
	 * @author Valentino-Jivko Radosavlevici
	 */
	class settings_l
	{
		
		/*
		 * Settings prefix
		 */
		var $prefix = '';
		
		/**
		 * Constructor
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function __construct()
		{
			// Set the default prefix
			$this->_prefix(true);
			
			// Load the SQL library
			$this->sql = octoms('sql',OMS_CL);
			
		}// end function __construct()
		
		/**
		 * Change the prefix
		 * 
		 * @example 
		 * // Set the prefix to blank - in order to access default WordPress options
		 * {settings}->_prefix();
		 * // Set the prefix to 'foo'
		 * {settings}->_prefix('foo');
		 * // Revert to the default prefix
		 * {settings}->_prefix(true);
		 * 
		 * @param mixed $p - True for the default prefix, null for blank, string for custom prefix
		 * @param string $returnDefault - Set to True to return the default prefix instead of {settings_l}
		 * @return {settings_l}
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function _prefix($p=null,$returnDefault=false)
		{
			if ($returnDefault)
			{
				return 'octoms_'.strtolower(ADMINSLUG).'_';
			}
			
			if ($p === true)
			{
				$this->prefix = 'octoms_'.strtolower(ADMINSLUG).'_';
			}
			else 
			{
				if (is_string($p))
				{
					$this->prefix = $this->_clean($p);
				}
				else 
				{
					$this->prefix = '';
				}
			}
			
			return $this;
		}// end function _prefix()
		
		/**
		 * Clean the option name helper
		 * 
		 * @param string $name - Option name
		 * @return string - cleaned option name
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function _clean($name)
		{
			// No uppercase characters; 0-9,a-z, underscore separated
			return strtolower(str_replace(' ', '_', preg_replace('%[^0-9a-z \_]%i', '', $name)));
		}// end function _clean()
		
		/**
		 * Get an option
		 * 
		 * // Get the 'foo' option
		 * {settings}->get('foo');
		 * // Get all the options associated with this theme
		 * {settings}->get();
		 * 
		 * @param string $option
		 * @return mixed - Null if the option was not set, mixed otherwise
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function get($option=null)
		{
			if (!is_null($option))
			{
				$data = get_option($this->prefix.$this->_clean($option),null);
				if ($this->prefix == $this->_prefix(null,true))
				{
					return $this->sql->unserialize($data);
				}
				else 
				{
					return $data;
				}
			}
			else 
			{
				// Prepare the query
				$q = strlen($this->prefix)>0 ?
					$this->sql->_select(
						null,
						$this->sql->wpdb->options,
						$this->sql->_where(
							array(
								'option_name' => $this->prefix.'%',
								$this->sql->LIKE
							)
						)
					)
					:
					$this->sql->_select(
						null,
						$this->sql->wpdb->options
					);

				// Query the database
				if ($this->sql->query($q)->num_rows()>0)
				{
					// Prepare the final result
					$get = array();
					foreach ($this->sql->rows() AS $r)
					{
						// Get the key
						$key = (strlen($this->prefix)>0) ? str_replace($this->prefix, '', $r['option_name']) : $r['option_name'];
						
						// Get the value
						$value = $r['option_value'];
						if ($value == '1') $value = true;
						if ($value == '') $value = false;
						
						// Append the result
						$get[$key] = $value;
					}
					
					// All done
					return count($get)>0?$get:null;
				}
				// No results
				else 
				{
					return null;
				}
				
			}
		}// end function get()
		
		/**
		 * Install procedure
		 * 
		 * @example 
		 * 
		 * @param string CSV filename
		 * @return 
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function install($file=NULL)
		{
			// This is mandatory
			if (is_null($file))
			{
				$file = 'wp_options.csv';
			}
			
			// Set the location
			$f = APP_ROOT.DS.'stages'.DS.'install'.DS.$file;
			
			// Load the mandatory libraries
			$csv = octoms('csv',OMS_CL);
			$template = octoms('template',OMS_L);
			
			// Start the session
			octoms('session',OMS_CL)->start();
			
			// Is this really the first time use?
			if (null === $this->get() || count($this->get())==1)
			{
				// Try to install the theme
				try 
				{
					// Get all the CSV rows
					if(file_exists($f) && count($rows=$csv->open($f)->rowGet())>0)
					{
						// Count the database inserts
						$inserts = 0;
						
						// Get each row
						foreach ($rows AS $r)
						{
							if (is_array($r) && count($r) > 4)
							{
								if (preg_match('%^'.$this->_prefix(null,true).'%', $r[2]))
								{
									// Get the name
									$name = preg_replace('%^'.$this->_prefix(null,true).'%', '', $r[2]);
									
									// Get the value
									if (null !== $value = $this->sql->unserialize($r[3]))
									{
										// Install the option
										$this->set($name,$value);
										
										// Count this insert
										$inserts++;
									}
								}
							}
						}
						
						// Any good rows?
						if ($inserts>0)
						{
							$template->_api('Theme '.WP_OCTOMS_TITLE.' installed successfully with '.$inserts.' options set. Thank you!');
						}
						else 
						{
							$template->_api('Theme '.WP_OCTOMS_TITLE.' installed successfully but please consider removing file "'.$f.'". Thank you!','info');
						}
					}
					else 
					{
						// As far as the user knows, everything went OK
						$template->_api('Theme '.WP_OCTOMS_TITLE.' installed successfully. Thank you!');
					}
				}
				catch (Exception $e)
				{
					// Something went wrong
					$template->_api('Default data could not be installed. '.$e->getMessage(),false);
				}
			}
			else 
			{
				$template->_api('Theme '.WP_OCTOMS_TITLE.' already in use.','warning');
			}
			
		}// end function install()
		
		/**
		 * Is option set?
		 * 
		 * // Is option 'foo' set?
		 * {settings}->is_set('foo');
		 * // Is there any option set?
		 * {settings}->is_set();
		 * 
		 * @param string $option
		 * @return boolean - True if the option was set, False otherwise
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function is_set($option=null)
		{
			return null !== $this->get($option);
		}// end function is_set()
		
		/**
		 * Reset an option
		 * 
		 * // Reset the "foo" option
		 * {settings}->reset('foo');
		 * // Reset all options associated with this theme
		 * {settings}->reset();
		 * 
		 * @param string $option
		 * @return boolean - True on success, False on failure
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function reset($option=null)
		{
			if (!is_null($option))
			{
				// Option set?
				if (null !== get_option($this->prefix.$this->_clean($option),null))
				{
					return delete_option($this->prefix.$option);
				}
				
				return false;
			}
			else 
			{
				// Prevent accidental deletion of default WordPress options
				if ($this->prefix !== $this->_prefix(true,true))
				{
					return false;
				}
				else 
				{
					// Delete all from database
					$this->sql->query(
						$this->sql->_delete(
							$this->sql->wpdb->options,
							$this->sql->_where(
								array(
									'option_name' => $this->prefix.'%',
									$this->sql->LIKE
								)
							)
						)
					);
					
					// All done
					return $this->sql->result?true:false; 
				}
			}
			
		}// end function reset()
		
		/**
		 * Set an option
		 * 
		 * // Set 'foo' as 'bar'
		 * {settings}->set('foo','bar');
		 * // Set 'foo' to True
		 * {settings}->set('foo');
		 * 
		 * @param string $option
		 * @param string $value
		 * @return boolean - True on success, False on failure
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function set($option=null,$value=true)
		{
			// The option name is mandatory
			if (is_null($option))
			{
				return false;
			}
			
			// Update?
			if (null !== get_option($this->prefix.$this->_clean($option)))
			{
				return update_option(
					$this->prefix.$this->_clean($option), 
					($this->prefix==''?$value:$this->sql->serialize($value))
				);
			}
			// Add
			else
			{
				return add_option(
					$this->prefix.$this->_clean($option),
					($this->prefix==''?$value:$this->sql->serialize($value))
				);
			}
		}// end function set()
		
	}// end class settings_l
	
	
/* End Of File <settings.inc> */